import pygame
from pytmx import load_pygame

from actor.japanese_soldier import JapaneseWalkSoldier
from actor.prizes import PrizesSprite
from actor.red_army_soldier import RedArmyShootSoldier
from sence import BaseScene


class TunnelWarScene(BaseScene):
    def __init__(self, xiao_tie):
        super(TunnelWarScene, self).__init__(xiao_tie, "./resources/tmx/tunnel_map.png")
        self.tiled_map_data = load_pygame("./resources/tmx/tunnel_map_1.tmx")
        self.obstacle_group = pygame.sprite.Group()
        self.japanese_group = pygame.sprite.Group()
        self.prizes_group = pygame.sprite.Group()
        self.init_actor()

    def init_actor(self):
        self.jian_jun = None
        self.tie_tou = None
        for group in self.tiled_map_data.objectgroups:
            if group.name == "日本人":
                for obj in group:
                    japanese = JapaneseWalkSoldier(obj.x, obj.y)
                    self.japanese_group.add(japanese)
            elif group.name == "奖品":
                for obj in group:
                    prizes = PrizesSprite(obj.x, obj.y)
                    prizes.rect = pygame.Rect(obj.x, obj.y, obj.width, obj.height)
                    self.prizes_group.add(prizes)
            elif group.name == "障碍物":
                for obj in group:
                    obstacle = pygame.sprite.Sprite()
                    obstacle.rect = pygame.Rect(obj.x, obj.y, obj.width, obj.height)
                    self.obstacle_group.add(obstacle)
            elif group.name == "解放军":
                for obj in group:
                    if obj.name == "建军":
                        self.jian_jun = RedArmyShootSoldier(obj.x, obj.y)
                    if obj.name == "铁头":
                        self.tie_tou = RedArmyShootSoldier(obj.x, obj.y)
            elif group.name == "小铁":
                for obj in group:
                    if obj.name == "小铁":
                        self.xiao_tie.set_pos(obj.x, obj.y)

    def draw_actor(self):
        self.xiao_tie.draw(self.current_surface, self.view_x, self.view_y)
        for japanese in self.japanese_group:
            japanese.draw(self.current_surface, self.view_x, self.view_y)
        self.tie_tou.draw(self.current_surface, self.view_x, self.view_y)
        self.jian_jun.draw(self.current_surface, self.view_x, self.view_y)

        for prizes in self.prizes_group:
            prizes.draw(self.current_surface, self.view_x, self.view_y)
        for obj in self.obstacle_group:
            x, y, w, h =obj.rect
            pygame.draw.rect(self.current_surface, pygame.Color(255, 0, 0),
                             (x - self.view_x, y - self.view_y, w, h), 1)

    def run(self, down_flag, key_list):
        self.xiao_tie.run(down_flag, key_list, self.obstacle_group)

        for japanese in self.japanese_group:
            japanese.run(down_flag, key_list, self.obstacle_group)
